package com.leonardo.beanme.metadatahandlers.tags;

import org.xml.sax.Attributes;

import MAR.Core.Reflector;

import com.leonardo.beanme.exceptions.ValidationException;
import com.leonardo.beanme.exceptions.XmlReadingException;
import com.leonardo.beanme.fields.InputField;
import com.leonardo.beanme.metadatahandlers.FieldMetadataContainer;
import com.leonardo.beanme.metadatahandlers.TagHandler;
import com.leonardo.beanme.model.BeanForm;

public class FieldTagHandler extends TagHandler {

	private boolean insideFieldTag = false;
	private String name;
	
	public String getTagName() {
		return "field";
	}

	public void endTag() {
		super.endTag();
		owner.getBeanInfo().addField(owner.getFieldInfo());
		insideFieldTag = false;
	}

	public void startTag(Attributes attributes) {
		if(insideFieldTag)
			throw new XmlReadingException("Incorrect place of tag field");
		System.out.println("Start field tag");
		getNameProperty(attributes);
		owner.setFieldInfo(new FieldMetadataContainer());
		insideFieldTag = true;
	}
	
	private void getNameProperty(Attributes attributes) {
		int nameIndex = attributes.getIndex("name");
		if(nameIndex < 0)
			throw new XmlReadingException("Missing name attribute in field inside bean " 
					+ owner.getBeanInfo().getId());
		name = attributes.getValue(nameIndex);
	}
	
	public void handle(InputField field, BeanForm form) {
		try {
			if(!((Reflector)BeanForm.getType().newInstance()).fieldExists(name))
				throw new ValidationException("Bean has no field named " + name);
			field.setName(name);
		} catch(Exception ex) {
			//never should happen
			ex.printStackTrace();
		}
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
}
